<template>
  <div class="video-view">
    <!-- 导航栏 -->
    <div class="navbar">
      <a @click="goBack" class="navbar-back">
        <i class="fas fa-arrow-left"></i>
      </a>
      <div class="navbar-title">宠物视频</div>
      <div @click="goToUpload">
        <i class="fas fa-upload"></i>
      </div>
    </div>
    
    <!-- 搜索栏 -->
    <div class="header">
      <div class="search-bar">
        <i class="fas fa-search search-icon"></i>
        <input 
          type="text" 
          class="search-input" 
          placeholder="搜索视频" 
          v-model="searchQuery"
          @input="handleSearch"
        >
      </div>
    </div>
    
    <!-- 分类导航 -->
    <div class="category-nav">
      <div 
        v-for="(category, index) in categories" 
        :key="index"
        :class="['category-item', { active: currentCategory === category.tagId }]"
        @click="selectCategory(category.tagId)"
      >
        {{ category.name }}
      </div>
    </div>
    
    <!-- 视频列表 -->
    <div class="container" v-if="!loading">
      <router-link 
        :to="{ name: 'VideoPlayer', params: { id: video.id } }" 
        class="video-card" 
        v-for="video in videos" 
        :key="video.id"
      >
        <div class="video-thumbnail">
          <img :src="video.coverUrl" :alt="video.title">
          <div class="video-play-icon">
            <i class="fas fa-play"></i>
          </div>
          <div class="video-duration">{{ formatDuration(video.duration) }}</div>
          <div class="prod-badge" v-if="video.hasProducts">
            <i class="fas fa-shopping-bag prod-icon"></i>
            <span>购买相关商品</span>
          </div>
        </div>
        <div class="video-info">
          <h3 class="video-title">{{ video.title }}</h3>
          <div class="video-meta">
            <div class="video-author">
              <img class="author-avatar" :src="video.author.avatar" :alt="video.author.name">
              <span>{{ video.author.name }}</span>
            </div>
            <div class="video-stats">
              <div class="stat-item">
                <i class="fas fa-eye stat-icon"></i>
                <span>{{ formatNumber(video.viewCount) }}</span>
              </div>
              <div class="stat-item">
                <i class="fas fa-thumbs-up stat-icon"></i>
                <span>{{ formatNumber(video.likeCount) }}</span>
              </div>
            </div>
          </div>
        </div>
      </router-link>
    </div>
    
    <!-- 加载中状态 -->
    <div class="loading-container" v-if="loading">
      <div class="loading-spinner">
        <i class="fas fa-spinner fa-spin"></i>
        <span>加载中...</span>
      </div>
    </div>
    
    <!-- 底部导航栏 -->
    <TabBar />
  </div>
</template>

<script>
import { ref, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import axios from 'axios'
import TabBar from '@/components/TabBar.vue'
import api from '@/network/api'

export default {
  name: 'VideoView',
  setup() {
    const router = useRouter()
    const videos = ref([])
    const loading = ref(true)
    const categories = ref([])
    const currentCategory = ref(1)
    const searchQuery = ref('')
    const searchTimeout = ref(null)

    // 获取视频分类列表
    const fetchCategories = async () => {
      try {
        const response = await api.getVideoCategories()
        categories.value = response.data.data
      } catch (error) {
        console.error('获取视频分类失败:', error)
      }
    }

    // 获取视频列表
    const fetchVideos = async () => {
      loading.value = true
      try {
        const response = await api.getVideos({
            category: currentCategory.value,
            query: searchQuery.value
        })
        videos.value = response.data.items
      } catch (error) {
        console.error('获取视频列表失败:', error)
      } finally {
        loading.value = false
      }
    }

    // 选择分类
    const selectCategory = (categoryId) => {
      currentCategory.value = categoryId
    }

    // 处理搜索
    const handleSearch = () => {
      if (searchTimeout.value) {
        clearTimeout(searchTimeout.value)
      }
      searchTimeout.value = setTimeout(() => {
        fetchVideos()
      }, 500)
    }

    // 格式化数字（如1200 -> 1.2万）
    const formatNumber = (num) => {
      if (num >= 10000) {
        return (num / 10000).toFixed(1) + '万'
      }
      return num.toString()
    }

    // 格式化视频时长（秒转为MM:SS）
    const formatDuration = (seconds) => {
      const minutes = Math.floor(seconds / 60)
      const remainingSeconds = seconds % 60
      return `${minutes}:${remainingSeconds.toString().padStart(2, '0')}`
    }

    // 返回上一页
    const goBack = () => {
      router.back()
    }

    // 前往上传页面
    const goToUpload = () => {
      router.push('/video/upload')
    }

    // 监听分类变化
    watch(currentCategory, () => {
      fetchVideos()
    })

    onMounted(() => {
      fetchCategories()
      fetchVideos()
    })

    return {
      videos,
      loading,
      categories,
      currentCategory,
      searchQuery,
      selectCategory,
      handleSearch,
      formatNumber,
      formatDuration,
      goBack,
      goToUpload
    }
  }
}
</script>

<style scoped>
/* 导航栏样式 */
.navbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  background-color: white;
  border-bottom: 1px solid #e2e8f0;
}

.navbar-back {
  font-size: 18px;
  color: #4a5568;
}

.navbar-title {
  font-size: 18px;
  font-weight: 500;
}

/* 头部搜索栏样式 */
.header {
  padding: 15px;
  background-color: white;
  box-shadow: 0 1px 3px rgba(0,0,0,0.05);
}

.search-bar {
  display: flex;
  align-items: center;
  background-color: #f1f5f9;
  border-radius: 20px;
  padding: 8px 15px;
}

.search-icon {
  color: #94a3b8;
  margin-right: 8px;
}

.search-input {
  border: none;
  background-color: transparent;
  outline: none;
  flex: 1;
  font-size: 14px;
}

/* 分类导航栏样式 */
.category-nav {
  display: flex;
  overflow-x: auto;
  white-space: nowrap;
  background-color: white;
  border-bottom: 1px solid #e2e8f0;
  padding: 10px 0;
}

.category-item {
  padding: 5px 15px;
  color: #4a5568;
  font-size: 14px;
}

.category-item.active {
  color: #3490dc;
  font-weight: 500;
  position: relative;
}

.category-item.active:after {
  content: '';
  position: absolute;
  bottom: -10px;
  left: 20%;
  right: 20%;
  height: 2px;
  background-color: #3490dc;
}

/* 视频卡片样式 */
.video-card {
  background-color: white;
  margin: 15px;
  border-radius: 10px;
  overflow: hidden;
  box-shadow: 0 2px 5px rgba(0,0,0,0.05);
  text-decoration: none;
  color: inherit;
  display: block;
}

.video-thumbnail {
  position: relative;
  width: 100%;
  height: 200px;
}

.video-thumbnail img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.video-play-icon {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 50px;
  height: 50px;
  background-color: rgba(0,0,0,0.5);
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.video-play-icon i {
  color: white;
  font-size: 20px;
}

.video-duration {
  position: absolute;
  bottom: 10px;
  right: 10px;
  background-color: rgba(0,0,0,0.6);
  color: white;
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 12px;
}

.prod-badge {
  position: absolute;
  bottom: 10px;
  left: 10px;
  background-color: rgba(52, 144, 220, 0.8);
  color: white;
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 12px;
  display: flex;
  align-items: center;
}

.prod-icon {
  margin-right: 3px;
  font-size: 10px;
}

.video-info {
  padding: 12px;
}

.video-title {
  font-size: 16px;
  font-weight: 500;
  color: #2d3748;
  margin-bottom: 8px;
}

.video-meta {
  display: flex;
  justify-content: space-between;
  color: #718096;
  font-size: 12px;
}

.video-author {
  display: flex;
  align-items: center;
}

.author-avatar {
  width: 20px;
  height: 20px;
  border-radius: 50%;
  margin-right: 5px;
  object-fit: cover;
}

.video-stats {
  display: flex;
}

.stat-item {
  display: flex;
  align-items: center;
  margin-left: 10px;
}

.stat-icon {
  margin-right: 3px;
}

/* 底部导航样式 */
.tabbar {
  display: flex;
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: white;
  box-shadow: 0 -1px 3px rgba(0,0,0,0.1);
  z-index: 10;
}

.tab-item {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 10px 0;
  color: #4a5568;
  text-decoration: none;
}

.tab-item.active {
  color: #3490dc;
}

.tab-icon {
  font-size: 20px;
  margin-bottom: 3px;
}

.tab-item span {
  font-size: 12px;
}

/* 加载状态样式 */
.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200px;
}

.loading-spinner {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.loading-spinner i {
  font-size: 24px;
  color: #3490dc;
  margin-bottom: 10px;
}

/* 容器样式，为底部导航腾出空间 */
.container {
  padding-bottom: 60px;
}

/* 视图容器 */
.video-view {
  min-height: 100vh;
  background-color: #f8fafc;
}
</style>
